package com.detrum.sportcamera.nfstask;

import android.content.Context;
import android.os.AsyncTask;

import com.detrum.NFSVideo;
import com.detrum.base.BaseStatic;
import com.detrum.bean.FileBean;
import com.detrum.sqlite.SqliteMediaOperation;
import com.detrum.utils.LogUtils;
import com.detrum.utils.NfsUtil;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;


/**
 * Created by abc on 2018/2/6.
 */

public class NfsLoadSingle extends AsyncTask<Void, FileBean, String> {
    private Context context;
    private ArrayList<FileBean> beanList;
    private int index;
    private LoadSingleCall loadSingleCall;
    private boolean isStop;

    public NfsLoadSingle(Context context, ArrayList<FileBean> list, int index, LoadSingleCall loadSingleCall) {
        this.context = context;
        beanList = new ArrayList<>();
        beanList.addAll(list);
        this.index = index;
        this.loadSingleCall = loadSingleCall;
    }

    public void setBeanList(ArrayList<FileBean> list){
        if(beanList==null){
            beanList = new ArrayList<>();
        }
        if(beanList!=null){
            beanList.addAll(list);
        }
    }

    public void Stop(){
        isStop = true;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        loadSingleCall.loadFinish();
    }

    @Override
    protected void onProgressUpdate(FileBean... values) {
        super.onProgressUpdate(values);
        loadSingleCall.sendSingle(values[0],values[0].getPosition());
    }

    @Override
    protected String doInBackground(Void... voids) {
        if (beanList != null && beanList.size() != 0) {
            while (true) {
                if(isStop){
                    break;
                }
                if(beanList.size()<=0){
                    break;
                }
                FileBean fileBean = beanList.remove(0);
                String fileName = fileBean.getFileName();
                if (NfsUtil.isImageFile(fileName)) {    //图片文件
                    String cachePath = fileBean.getCachePath();
                    LogUtils.e("LoadSingle cachePath = "+cachePath);
                    File cacheFile = null;
                    if (cachePath != null) {
                        cacheFile = new File(cachePath);
                    }else{
                        File cacheDir = new File(BaseStatic.MediaPath);
                        if (!cacheDir.exists()) {
                            cacheDir.mkdirs();
                        }
                        cacheFile = new File(cacheDir, fileName);
                    }
                    if (cacheFile != null && cacheFile.length() != 0) {//缓存中存在同样的文件
                        fileBean.setCachePath(cacheFile.getPath());
                        fileBean.setSize(cacheFile.length());
                        SqliteMediaOperation.getInstence(context).UpdataItem(fileBean, fileName);
                        continue;
                    } else {
                        byte[] imageData = LoadImage(fileBean);
                        LogUtils.i("imageData is "+imageData.length);
                        if (imageData == null||imageData.length==0) {
                            LogUtils.i("imageData is null");
                            continue;
                        }
                        //publishProgress(fileBean);
                        loadSingleCall.loadImageStart(fileBean);
                        try {
                            FileOutputStream fos = new FileOutputStream(cacheFile);
                            fos.write(imageData);
                            fos.flush();
                            fos.close();
                            fileBean.setCachePath(cacheFile.getPath());
                            fileBean.setSize(cacheFile.length());
                            SqliteMediaOperation.getInstence(context).UpdataItem(fileBean, fileName);
                            LogUtils.i(cacheFile.getPath()+"----------"+cacheFile.length());
                            publishProgress(fileBean);
                            continue;
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                            continue;
                        } catch (IOException e) {
                            e.printStackTrace();
                            continue;
                        }
                    }
                } else if (NfsUtil.isVideoFile(fileName)) {
                    String thumbPath = fileBean.getThumbPath();
                    if(thumbPath!=null&&thumbPath.length()!=0){
                        File thumb = new File(thumbPath);
                        if(thumb==null||thumb.length()==0){
                            fileBean.setThumbPath(null);
                            publishProgress(fileBean);
                        }
                        continue;
                    }
                    String name = fileName.toLowerCase();
                    if (fileName.contains(".mp4")) {
                        name = fileName.replace(".mp4", ".jpg");
                    } else if (fileName.contains(".mov")) {
                        name = fileName.replace(".mov", ".jpg");
                    }
                    File thumbFile = new File(BaseStatic.ThumbPath);
                    if(!thumbFile.exists()){
                        thumbFile.mkdirs();
                    }
                    thumbFile = new File(thumbFile, name);
                    if (thumbFile.exists()&&thumbFile.length()!=0) {//缓存中存在同样的文件
                        // TODO: 2018/2/10 此处没有播放总时间
                        LogUtils.e("LoadSingle thumbPath = "+thumbFile.getPath());
                        fileBean.setThumbPath(thumbFile.getPath());
                        SqliteMediaOperation.getInstence(context).UpdataItemThumbPath(thumbFile.getPath(), fileName);
                    }
                    publishProgress(fileBean);
                }
            }
        }
        return null;
    }

    private byte[] LoadImage(FileBean fileBean) {
        int flag = -1;
        byte[] bytes = new byte[(int) fileBean.getSize()];
        flag = NFSVideo.open(fileBean.getNfsPath(), 0, index);
        if (flag < 0) {
            NFSVideo.close(index);
            loadSingleCall.avGetFail(fileBean);
            return null;
        }
        flag = NFSVideo.read(bytes, bytes.length, index);
        if (flag < 0) {
            NFSVideo.close(index);
            loadSingleCall.avGetFail(fileBean);
            return null;
        }
        NFSVideo.close(index);
        return bytes;
    }


}
